package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;

/**
 * @Description 解析server.xml
 * @Date 2021/8/16 16:09
 * @Created by mike
 */
public class ServerLoader {

    private static Server server = new Server();

    private ServerLoader(){}

    public static Server getServer(){
        return server;
    }

    static {
        new ServerLoader().parseServer();
    }

    private void parseServer() {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        Document rootDocument = null;
        try {
            rootDocument = saxReader.read(inputStream);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Node service = rootDocument.selectSingleNode("//service");
        Element connector = (Element) rootDocument.selectSingleNode("//connector");
        String port = connector.attributeValue("port"); // 8080
        Node engine = service.selectSingleNode("//engine");
        Element host = (Element) engine.selectSingleNode("//host");
        String hostName = host.attributeValue("name"); // localhost
        String appBase = host.attributeValue("appBase"); // E:\learn\lagou\stage2\module1\TomcatAndNginx\code\Minicat\src\main\resources\webapps
        server.setPort(port);
        server.setHost(hostName);
        server.setAppBase(appBase);
    }
}
